package com.xca.daggerdemo.database;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;


import com.xca.daggerdemo.entity.Student;

import java.util.ArrayList;
import java.util.List;

public class DBHelper extends SQLiteOpenHelper {

    private static final String TAG = "DBHelper";
    private static final String DATABASE_NAME = "db_student_manager";// 数据库名
    private static final int DATABASE_VERSION = 1;// 数据库版本号
    private static final String TABLE_NAME_STUDENT = "student"; //学生表

    //private static DBHelper mHelper = null;
    public DBHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    //单例模式
   /*public static DBHelper getInstance(Context context){
      if(mHelper == null){
         mHelper = new DBHelper(context);
      }
      return mHelper;
   }*/

    //数据库创建时被调用
    @Override
    public void onCreate(SQLiteDatabase db) {
        initTable(db);
        initData(db);
    }

    //数据库升级
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    /**
     * 初始化数据表
     *
     * @param db 数据库
     */
    private void initTable(SQLiteDatabase db) {
        // 创建学生表
        db.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_NAME_STUDENT + " (" +
                "_id integer primary key autoincrement," +
                "student_name text," +
                "student_code text," +
                "username text," +
                "password text," +
                "class_name text)");
    }

    /**
     * 初始化数据库内部数据(仅在第一次安装时执行)
     *
     * @param db 数据库
     */
    private void initData(SQLiteDatabase db) {
        db.execSQL("insert into " + TABLE_NAME_STUDENT +
                " (student_name , student_code, username, password, class_name) " +
                "values" +
                "('张老三', '202100000001', 'helloworld', '12345678', '计算机1班')");
        db.execSQL("insert into " + TABLE_NAME_STUDENT +
                " (student_name , student_code, username, password, class_name) " +
                "values" +
                "('李老四', '202100000002', 'helloworld', 'abcdefgh', '计算机2班')");
        db.execSQL("insert into " + TABLE_NAME_STUDENT +
                " (student_name , student_code, username, password, class_name) " +
                "values" +
                "('王老五', '202100000003', '你好和都很好的', 'aaaaaaaa', '计算机3班')");
        db.execSQL("insert into " + TABLE_NAME_STUDENT +
                " (student_name , student_code, username, password, class_name) " +
                "values" +
                "('刘老六', '202100000004', 'myname', '66665678', '计算机4班')");
    }

    public void insertStudent(Student student) {
        SQLiteDatabase db = getWritableDatabase();
        db.execSQL("insert into " + TABLE_NAME_STUDENT +
                " (student_name , student_code, username, password, class_name) " +
                "values" +
                "('" + student.getStudent_name() + "','" + student.getStudent_code() + "','" + student.getUsername() + "','" + student.getPassword() + "','" + student.getClass_name() + "')");
    }

    public void insertStudent2(Student student) {
        //获取可写数据库
        SQLiteDatabase db = getWritableDatabase();

        //创建ContentValues以Key-Value的形式封装数据
        ContentValues values = new ContentValues();
        values.put("student_name", student.getStudent_name());
        values.put("student_code", student.getStudent_code());
        values.put("username", student.getUsername());
        values.put("password", student.getPassword());
        values.put("class_name", student.getClass_name());

        //执行insert方法，插入数据
        long newRowId = db.insert(TABLE_NAME_STUDENT, null, values);
        Log.d(TAG, "insertStudent2 newRowId = " + newRowId);
    }

    public void deleteStudentByName(String name) {
        if (name != null) {
            SQLiteDatabase db = getReadableDatabase();
            int changedRowCount = db.delete(TABLE_NAME_STUDENT, "student_name = ?", new String[]{name});
            Log.d(TAG, "deleteStudentByName changedRowCount = " + changedRowCount);
        }
    }

    public void updateStudentNameById(String name, int id) {
        if (name != null && id >= 0) {
            SQLiteDatabase db = getReadableDatabase();
            ContentValues values = new ContentValues();
            values.put("student_name", name);
            int changedRowCount = db.update(TABLE_NAME_STUDENT, values, "_id = ?", new String[] {String.valueOf(id)});
            Log.d(TAG, "updateStudentNameById changedRowCount = " + changedRowCount);
        }
    }

    @SuppressLint("Range")
    public List<Student> selectAllStudent() {
        List<Student> list = new ArrayList<>();
        SQLiteDatabase db = getReadableDatabase();

        Cursor cursor = db.query(
                TABLE_NAME_STUDENT,     // 表名
                null,                   // 要查询的列数据
                null,                   // 条件语句
                null,                   // 条件语句的值
                null,                   // group by
                null,                   // having
                null                    // 排序语句
        );
        if (cursor != null && cursor.getCount() > 0) {
            while (cursor.moveToNext()) {
                Student student = new Student();
                student.setStudent_id(cursor.getInt(cursor.getColumnIndex("_id")));
                student.setStudent_name(cursor.getString(cursor.getColumnIndex("student_name")));
                student.setStudent_code(cursor.getString(cursor.getColumnIndex("student_code")));
                student.setUsername(cursor.getString(cursor.getColumnIndex("username")));
                student.setPassword(cursor.getString(cursor.getColumnIndex("password")));
                student.setClass_name(cursor.getString(cursor.getColumnIndex("class_name")));
                list.add(student);
            }
        }
        Log.d(TAG, "selectAllStudent = " + list.size());
        return list;
    }
}